<template>
	<view class="carbon">
		<view class="iData">
			<div class="iDatacontain ignore-carbon-top">
				<div class="top-img">
					<div class="topImg" v-for="item in carbonArray" :key="item.id">
						<div class="topnum">{{ item.num }}</div>
						<div class="topname">{{ item.name }}</div>
						<div class="topunit"
							:style="{background:'url('+item.src+') no-repeat',backgroundSize:'100% 100%'}">
							<div class="topitem">{{ item.unit }}</div>
						</div>
					</div>
				</div>
				<div class="bimg"></div>
			</div>
		</view>
		<view class="eData">
			<div class="eDatacenter">
				<div class="cTitle">
					<div class="edtitle">年碳排放量统计</div>
					<div class="edhengxian"></div>
				</div>
				<div class="linechart">
					<div class="piechart">
						<div class="tpf_title">
							<img :src="titleImage" class="title_one" />
							<div class="title_txt1">累计碳排放量</div>
							<div class="title_number">{{ total.toFixed(2) }}</div>
							<div class="title_unit">吨</div>
						</div>
						<div class="charts">
							<div id="carbon-echarts-center"></div>
						</div>
					</div>
				</div>
			</div>
		</view>
		<view class="tanpai">
			<div class="eDatacenter">
				<div class="cTitle">
					<div class="edtitle">减碳量各项占比</div>
					<div class="edhengxian"></div>
				</div>
				<div class="circlechart">
					<div class="at-echart-initializer boxShadowNone bgColor">
						<div class="at-card boxShadowNone">
							<div class="at-body">
								<div id="tan-dashboard-deviceTypeCount" style="width:100%;height:100%;"></div>
							</div>
						</div>
					</div>
				</div>
			</div>
		</view>
	</view>
</template>

<script>
	import * as echarts from 'echarts';
	const domId = 'carbon-echarts-center';
	const domUId = 'tan-dashboard-deviceTypeCount';
	import {
		carbonList
	} from "@/common/const_data.js";
	import {
		optionCarbonValue,
		optionCarbonEValue,
		tmp
	} from "@/common/echart_data.js";
	import request from '@/common/request.js';
	import $config from '@/common/config.js';
	import moment from "moment";
	export default {
		data() {
			return {
				titleImage: 'http://portal.xumengte.com/homeImg/Group86.png',
				total: 0,
				carbonArray: [],
				percentTotal: 0
			}
		},
		props: {
			index: Number
		},
		methods: {
			visualioneAction() {},
			// 饼图自动轮播
			handleChartLoop(option, myChart) {
				if (!myChart) {
					return
				}
				let currentIndex = -1 // 当前高亮图形在饼图数据中的下标
				// let changePieInterval = setInterval(selectPie, 5000) // 设置自动切换高亮图形的定时器
				selectPie()
				// 取消所有高亮并高亮当前图形
				function highlightPie() {
					// 遍历饼图数据，取消所有图形的高亮效果
					for (var idx in option.series[0].data) {
						myChart.dispatchAction({
							type: 'downplay',
							seriesIndex: 0,
							dataIndex: idx
						})
					}
					// 高亮当前图形
					myChart.dispatchAction({
						type: 'highlight',
						seriesIndex: 0,
						dataIndex: currentIndex
					})
				}

				// 用户鼠标悬浮到某一图形时，停止自动切换并高亮鼠标悬浮的图形
				myChart.on('mouseover', (params) => {
					// clearInterval(changePieInterval)
					currentIndex = params.dataIndex
					highlightPie()
				})

				// 用户鼠标移出时，重新开始自动切换
				myChart.on('mouseout', (params) => {
					// if (changePieInterval) {
					// 	clearInterval(changePieInterval)
					// }
					// changePieInterval = setInterval(selectPie, 5000)
				})

				// 高亮效果切换到下一个图形
				function selectPie() {
					var dataLen = option.series[0].data.length
					currentIndex = (currentIndex + 1) % dataLen
					highlightPie()
				}
			},
			//左上累计模块数据
			loadTotalFn() {
				request.get('/jeecgboot/statistic/carbon/data2?projectId=' + $config.pcode).then(resData => {
					console.log(resData, '------resData-----')
					carbonList[0].num = resData.result.totalPower.toFixed(0)
					carbonList[1].num = resData.result.savePower.toFixed(0)
					carbonList[2].num = resData.result.totalCarbon.toFixed(0)
					carbonList[3].num = resData.result.subCarbon.toFixed(0)


					let value0 = resData.result.subcarbon_building.toFixed(2)
					let value1 = resData.result.subcarbon_renewable.toFixed(2)
					let value2 = resData.result.subcarbon_greenCarbonSum.toFixed(2)

					if (value0 < value1) {
						tmp[0].value = value1
						tmp[0].name = '可再生能源'
						tmp[1].value = value0
						tmp[1].name = '建筑'
					} else {
						tmp[0].value = value0
						tmp[1].value = value1
					}
					tmp[2].value = value2
					tmp.forEach((el) => {
						this.percentTotal += Number(el.value);
					});
					tmp.forEach((el) => {
						el.precent = this.percentTotal > 0 && el.value > 0 ? Math.floor((el.value * 100) /
							this.percentTotal).toFixed(0) : 0;
					});
					optionCarbonEValue.legend.formatter = function(a) {
						let temIndex = tmp.findIndex(item => item.name == a)
						return `{whiteF|${a}} {ml|${tmp[temIndex].value}}   {ml2|${tmp[temIndex].precent}%}`;
					};
					// #ifdef H5
					// this.$nextTick(() => {
					let chartUDom = document.getElementById(domUId);
					let echartUInstance = echarts.init(chartUDom);
					echartUInstance.setOption(optionCarbonEValue);
					this.handleChartLoop(optionCarbonEValue, echartUInstance)
					// })
					// #endif
				}).catch(errData => {
					console.log(errData, '-----errData-----')
				})
			},
			//"年碳排放量统计模块"数据
			loadYeartpfDataFn() {
				let that = this
				let params = {
					timeType: "month",
					startTime: moment().year(moment().year() - 1).startOf("year").format("YYYY-MM-DD"),
					endTime: moment().year(moment().year() - 1).endOf("year").format("YYYY-MM-DD"),
					startTime2: moment().startOf('year').format('YYYY-MM-DD'),
					endTime2: moment().endOf('year').format('YYYY-MM-DD'),
					configId: 'power_all',
					projectId: $config.pcode,
				}
				request.postRaw('/jeecgboot/device/data/sameDiff', {
					"content-type": "application/json"
				}, params).then(res => {
					console.log(res, '------res-----')
					let range = res.result.mdRange[0];
					if (res.result.mdRange[0].length < res.result.mdRange[1].length) {
						range = res.result.mdRange[1];
					}
					optionCarbonValue.xAxis[0].data = range.map((item) => {
						return item.substring(5);
					});

					// mdData: 分前后2个部分， 包括：每个设备的数据，最后一条是加权计算过的数据
					optionCarbonValue.series[0].data = res.result.mdData.map((level1) => {
						let delData = level1
							.slice(0, level1.length / 2)
							.slice(-1)[0]
							?.power * 0.5703 / 1000

						//取最后一个 计算过的数据
						return !level1.slice(0, level1.length / 2).slice(-1)[0] ?
							0 :
							that.upFixed(delData, 4)
					});
					optionCarbonValue.series[1].data = res.result.mdData.map((level1) => {
						let delData1 = level1.slice(-1)[0]?.power * 0.5703 / 1000
						//取最后一个 计算过的数据
						return !level1.slice(-1)[0] ? 0 : that.upFixed(delData1, 4);
					});
					console.log(optionCarbonValue.series[1].data, '---- optionCarbonValue.series[1].data---')
					optionCarbonValue.series[1].data.forEach((v) => {
						if (v > 0) that.total -= -v;
					});

					this.$nextTick(() => {
						let chartDom = document.getElementById(domId);
						let echartInstance = echarts.init(chartDom);
						echartInstance.setOption(optionCarbonValue);
					});

				})
			},
			//"减碳量各项占比模块" 数据
			loadAllKindPercentDataFn() {

			},
			//"碳交易实时模块"数据
			loadCoalTransactionDataFn() {

			},

			//"碳减量分析模块"数据
			loadCoalAsyDataFn() {

			},

			upFixed(num, fix) {
				// num为原数字，fix是保留的小数位数
				let result = '0'
				if (Number(num) && fix > 0) { // 简单的做个判断
					fix = +fix || 2
					num = num + ''
					if (/e/.test(num)) { // 如果是包含e字符的数字直接返回
						result = num
					} else if (!/\./.test(num)) { // 如果没有小数点
						result = num + `.${Array(fix + 1).join('0')}`
					} else { // 如果有小数点
						num = num + `${Array(fix + 1).join('0')}`
						let reg = new RegExp(`-?\\d*\\.\\d{0,${fix}}`)
						let floorStr = reg.exec(num)[0]
						if (+floorStr >= +num) {
							result = floorStr
						} else {
							let floorNumber = +floorStr + +`0.${Array(fix).join('0')}1`
							let point = /\./.test(floorNumber + '') ? '' : '.'
							let floorStr2 = floorNumber + point + `${Array(fix + 1).join('0')}`
							result = reg.exec(floorStr2)[0]
						}
					}
				}
				return result
			}
		},
		created() {
			console.log('created==>>')
			this.loadTotalFn()
			this.loadYeartpfDataFn()
		},
		mounted() {
			this.carbonArray = carbonList;
			// this.$nextTick(() => {
			// 	let chartDom = document.getElementById(domId);
			// 	let echartInstance = echarts.init(chartDom);
			// 	echartInstance.setOption(optionCarbonValue);

			// 	let chartUDom = document.getElementById(domUId);
			// 	let echartUInstance = echarts.init(chartUDom);
			// 	console.log(optionCarbonEValue, '--------finally-----')
			// 	echartUInstance.setOption(optionCarbonEValue);
			// 	this.handleChartLoop(optionCarbonEValue, echartUInstance)
			// });

		}
	}
</script>

<style scoped>
	@import 'index.css';
</style>
